<template>
  <div>
    <!-- Sidebar -->
    <div class="sidebar">
      <div style="padding: 24px 20px; border-bottom: 1px solid #e5e7eb;">
        <div style="display: flex; align-items: center;">
          <div style="width: 40px; height: 40px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 10px; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold; font-size: 18px;">快</div>
          <div style="margin-left: 12px;">
            <div style="font-weight: 600; color: #111827;">快递代拿管理系统</div>
          </div>
        </div>
      </div>

      <div style="padding: 16px 0;">
        <div class="nav-section">主菜单</div>
        <button :class="['nav-item', $route.path === '/admin/dashboard' ? 'active' : '']" @click="$router.push('/admin/dashboard')"><i class="fas fa-chart-line"></i><span>数据总览</span></button>
        <button :class="['nav-item', $route.path === '/admin/orders' ? 'active' : '']" @click="$router.push('/admin/orders')"><i class="fas fa-box"></i><span>订单管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/users' ? 'active' : '']" @click="$router.push('/admin/users')"><i class="fas fa-users"></i><span>下单者管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/couriers' ? 'active' : '']" @click="$router.push('/admin/couriers')"><i class="fas fa-motorcycle"></i><span>代拿者管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/finance' ? 'active' : '']" @click="$router.push('/admin/finance')"><i class="fas fa-wallet"></i><span>财务管理</span></button>

        <div class="nav-section">运营管理</div>
        <button :class="['nav-item', $route.path === '/admin/announcements' ? 'active' : '']" @click="$router.push('/admin/announcements')"><i class="fas fa-bullhorn"></i><span>公告管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/pricing' ? 'active' : '']" @click="$router.push('/admin/pricing')"><i class="fas fa-percentage"></i><span>盈利规则</span></button>
        

        <div class="nav-section">系统设置</div>
        <button :class="['nav-item', $route.path === '/admin/permissions' ? 'active' : '']" @click="$router.push('/admin/permissions')"><i class="fas fa-shield-alt"></i><span>权限管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/logs' ? 'active' : '']" @click="$router.push('/admin/logs')"><i class="fas fa-file-alt"></i><span>系统日志</span></button>
        <button :class="['nav-item', $route.path === '/admin/settings' ? 'active' : '']" @click="$router.push('/admin/settings')"><i class="fas fa-cog"></i><span>系统设置</span></button>
      </div>

      <div style="position: absolute; bottom: 0; left: 0; right: 0; padding: 20px; border-top: 1px solid #e5e7eb;">
        <div style="display: flex; align-items: center;">
          <div style="width: 40px; height: 40px; border-radius: 50%; background:#e5e7eb; display:flex; align-items:center; justify-content:center; color:#6b7280; font-weight:600;">管</div>
          <div style="margin-left: 12px; flex: 1;">
            <div style="font-weight: 500; color: #111827; font-size: 14px;">管理员</div>
            <div style="font-size: 12px; color: #9ca3af;">超级管理员</div>
          </div>
        </div>
        <button class="nav-item" @click="confirmLogout" style="margin-top:12px;"><i class="fas fa-sign-out-alt"></i><span>退出登录</span></button>
      </div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
      <!-- Header -->
      <div style="background: white; border-bottom: 1px solid #e5e7eb; padding: 16px 32px; display: flex; align-items: center; justify-content: space-between;">
        <div></div>
        <div style="position: relative;">
          <i class="fas fa-search" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #9ca3af;"></i>
          <input type="text" placeholder="搜索..." style="padding: 8px 12px 8px 36px; border: 1px solid #e5e7eb; border-radius: 8px; width: 240px; font-size: 14px;">
        </div>
      </div>

      <!-- Content -->
      <div style="padding: 32px;">
        <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 32px;">
          <div>
            <h1 style="font-size: 28px; font-weight: 700; color: #111827; margin-bottom: 8px;">盈利规则</h1>
            <p style="color: #6b7280;">配置平台抽成模式和盈利规则</p>
          </div>
        </div>

        <!-- 平台抽成配置 -->
        <div class="content-card">
          <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 24px;">
            <div>
              <h3 style="font-size: 18px; font-weight: 600; color: #111827; margin-bottom: 4px;">平台抽成配置</h3>
              <p style="color: #6b7280; font-size: 14px;">设置平台从订单中抽取的服务费比例</p>
            </div>
            <button 
              v-if="!isEditing"
              @click="startEdit" 
              style="padding: 10px 20px; background: #3b82f6; color: white; border: none; border-radius: 8px; cursor: pointer; font-size: 14px; font-weight: 500;"
            >
              <i class="fas fa-edit" style="margin-right: 8px;"></i>编辑规则
            </button>
          </div>

          <div v-if="!isEditing" style="background: #f9fafb; border-radius: 12px; padding: 32px;">
            <div style="text-align: center;">
              <div style="font-size: 48px; font-weight: 700; color: #3b82f6; margin-bottom: 8px;">{{ profitRule.commission_rate }}%</div>
              <div style="color: #6b7280; font-size: 16px; margin-bottom: 24px;">平台抽成比例</div>
              <div style="background: white; border-radius: 8px; padding: 20px; text-align: left; max-width: 600px; margin: 0 auto;">
                <div style="margin-bottom: 12px;">
                  <div style="font-weight: 500; color: #111827; margin-bottom: 4px;">规则类型</div>
                  <div style="color: #6b7280;">{{ profitRule.rule_type === 'commission_rate' ? '按比例抽成' : profitRule.rule_type }}</div>
                </div>
                <div style="margin-bottom: 12px;">
                  <div style="font-weight: 500; color: #111827; margin-bottom: 4px;">规则描述</div>
                  <div style="color: #6b7280;">{{ profitRule.description || '对于下单者自定义的订单价格，平台默认抽成' + profitRule.commission_rate + '%' }}</div>
                </div>
                <div>
                  <div style="font-weight: 500; color: #111827; margin-bottom: 4px;">状态</div>
                  <span class="status-badge status-active">{{ profitRule.is_active ? '已启用' : '已禁用' }}</span>
                </div>
              </div>
            </div>
          </div>

          <div v-else style="background: #f9fafb; border-radius: 12px; padding: 32px;">
            <div style="max-width: 600px; margin: 0 auto;">
              <div style="margin-bottom: 20px;">
                <label style="display: block; font-weight: 500; color: #111827; margin-bottom: 8px;">平台抽成比例 (%)</label>
                <input 
                  type="number" 
                  v-model.number="editForm.commission_rate" 
                  min="0" 
                  max="100" 
                  step="0.1"
                  style="width: 100%; padding: 12px; border: 1px solid #e5e7eb; border-radius: 8px; font-size: 16px;"
                  placeholder="请输入抽成比例"
                />
                <div style="color: #6b7280; font-size: 13px; margin-top: 4px;">设置平台从每笔订单中抽取的百分比（0-100）</div>
              </div>
              <div style="margin-bottom: 20px;">
                <label style="display: block; font-weight: 500; color: #111827; margin-bottom: 8px;">规则描述</label>
                <textarea 
                  v-model="editForm.description"
                  rows="3"
                  style="width: 100%; padding: 12px; border: 1px solid #e5e7eb; border-radius: 8px; font-size: 14px; resize: vertical;"
                  placeholder="请输入规则描述"
                ></textarea>
              </div>
              <div style="display: flex; gap: 12px; justify-content: flex-end;">
                <button 
                  @click="cancelEdit" 
                  style="padding: 10px 20px; background: #f3f4f6; color: #374151; border: none; border-radius: 8px; cursor: pointer; font-size: 14px; font-weight: 500;"
                >
                  取消
                </button>
                <button 
                  @click="saveProfitRule" 
                  style="padding: 10px 20px; background: #3b82f6; color: white; border: none; border-radius: 8px; cursor: pointer; font-size: 14px; font-weight: 500;"
                >
                  保存
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 抽成说明 -->
        <div class="content-card">
          <h3 style="font-size: 18px; font-weight: 600; color: #111827; margin-bottom: 20px;">抽成规则说明</h3>
          <div style="background: #eff6ff; border-left: 4px solid #3b82f6; padding: 16px; border-radius: 4px;">
            <p style="color: #1e40af; line-height: 1.8; margin-bottom: 12px;">
              <strong>当前抽成规则：</strong>
            </p>
            <ul style="color: #1e40af; line-height: 1.8; padding-left: 20px; margin: 0;">
              <li>对于下单者自定义的订单价格，平台默认抽成 <strong>{{ profitRule.commission_rate }}%</strong></li>
              <li>抽成金额 = 订单最终价格 × {{ profitRule.commission_rate }}%</li>
              <li>代拿员实际收入 = 订单最终价格 - 平台抽成金额</li>
              <li>平台抽成用于维持平台运营、技术维护和客户服务</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { ElMessage } from 'element-plus'

export default {
  name: 'AdminPricing',
  data() {
    return {
      profitRule: {
        id: null,
        commission_rate: 10.00,
        rule_type: 'commission_rate',
        description: '对于下单者自定义的订单价格，平台默认抽成10%',
        is_active: true
      },
      isEditing: false,
      editForm: {
        commission_rate: 10.00,
        description: ''
      }
    }
  },
  methods: {
    confirmLogout() {
      if (confirm('是否确认退出？')) {
        localStorage.removeItem('adminToken')
        localStorage.removeItem('adminInfo')
        localStorage.removeItem('userToken')
        this.$router.push('/login')
      }
    },
    async fetchProfitRule() {
      try {
        const { data } = await axios.get('/api/admin/profit-rules')
        if (data && data.success) {
          this.profitRule = data.data || this.profitRule
        }
      } catch (e) {
        console.error('获取盈利规则失败', e)
      }
    },
    startEdit() {
      this.editForm = {
        commission_rate: this.profitRule.commission_rate,
        description: this.profitRule.description || ''
      }
      this.isEditing = true
    },
    cancelEdit() {
      this.isEditing = false
    },
    async saveProfitRule() {
      if (!this.profitRule.id) {
        // 创建新规则
        try {
          const { data } = await axios.post('/api/admin/profit-rules', {
            rule_name: '平台抽成规则',
            commission_rate: this.editForm.commission_rate,
            rule_type: 'commission_rate',
            description: this.editForm.description || `对于下单者自定义的订单价格，平台默认抽成${this.editForm.commission_rate}%`
          })
          if (data && data.success) {
            ElMessage.success('盈利规则保存成功')
            this.isEditing = false
            await this.fetchProfitRule()
          } else {
            ElMessage.error(data.message || '保存失败')
          }
        } catch (e) {
          console.error('保存盈利规则失败', e)
          ElMessage.error('保存失败，请重试')
        }
      } else {
        // 更新现有规则
        try {
          const { data } = await axios.put(`/api/admin/profit-rules/${this.profitRule.id}`, {
            commission_rate: this.editForm.commission_rate,
            description: this.editForm.description || `对于下单者自定义的订单价格，平台默认抽成${this.editForm.commission_rate}%`
          })
          if (data && data.success) {
            ElMessage.success('盈利规则更新成功')
            this.isEditing = false
            await this.fetchProfitRule()
          } else {
            ElMessage.error(data.message || '更新失败')
          }
        } catch (e) {
          console.error('更新盈利规则失败', e)
          ElMessage.error('更新失败，请重试')
        }
      }
    }
  },
  mounted() {
    this.fetchProfitRule()
  }
}
</script>

<style scoped>
.sidebar { position: fixed; left: 0; top: 0; width: 240px; height: 100vh; background: #fff; border-right: 1px solid #e5e7eb; overflow-y: auto; }
.main-content { margin-left: 240px; min-height: 100vh; }
.nav-item { display: flex; align-items: center; padding: 12px 20px; color: #6b7280; text-decoration: none; transition: all 0.2s; cursor: pointer; width: 100%; background: transparent; border: 0; text-align: left; }
.nav-item:hover { background: #f3f4f6; color: #3b82f6; }
.nav-item.active { background: #eff6ff; color: #3b82f6; font-weight: 500; }
.nav-item i { width: 20px; margin-right: 12px; }
.nav-section { padding: 16px 20px 8px; font-size: 12px; color: #9ca3af; font-weight: 500; text-transform: uppercase; letter-spacing: 0.5px; }
.content-card { background: white; border-radius: 12px; padding: 24px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin-bottom: 24px; }
.pricing-card { border: 2px solid #e5e7eb; border-radius: 12px; padding: 24px; transition: all 0.2s; }
.pricing-card:hover { border-color: #3b82f6; box-shadow: 0 4px 12px rgba(59, 130, 246, 0.1); }
.status-badge { display: inline-block; padding: 4px 12px; border-radius: 12px; font-size: 12px; font-weight: 500; }
.status-active { background: #d1fae5; color: #065f46; }
.status-inactive { background: #f3f4f6; color: #6b7280; }

table { width: 100%; border-collapse: collapse; }
th { text-align: left; padding: 12px; color: #6b7280; font-weight: 500; font-size: 13px; border-bottom: 1px solid #e5e7eb; }
 td { padding: 16px 12px; border-bottom: 1px solid #f3f4f6; color: #374151; }
</style>
